<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');


/**

 * Define css file

 */
 	function load_pages_cat()
	{
		$ci = & get_instance();
		$ci->load->model('Mpages');
	//	print_r($ci->db->where());
		return $data = $ci->Mpages->load_page_cat();
	}
 function unlink_file($file,$path)
 {
	// $path = "./upload/news/".$file[0]['news_images'];
	if(file_exists($path.$file))
			@unlink($path.$file);
	
 }
 function url()
 {
	 return base_url().'index.php/';
 }
 function online()
 {
 	$CI =& get_instance();
		$CI->load->model("Mcustomer");
		$count = $CI->Mcustomer->count_online();
			return $count;
 } 
 function member()
 {
 		$CI =& get_instance();
		$CI->load->model("Mcustomer");
		$count = $CI->Mcustomer->count_member_online();
		return $count;
 }
 
 // cout visted
 function count_view()
 {
 
 	$c  = & get_instance();
	$c->load->helper('file');
	$string = read_file("./public/images/counter.txt");
	//$fp=fopen("./images/counter.txt","a")or exit("100");
	//$count =fgets($fp);
	
//$fp = fopen('data.txt', 'w');
//fwrite($fp, '1');
//fwrite($fp, '23');
//$count =fgets($fp);
//fclose($fp);
$string++;


if ( ! write_file("./public/images/counter.txt", $string))
{
     echo 'Unable to write the file';
}
echo $string;



 }
 
 // set secure session 
 function set_secure_code($word)
 {
	 $c = & get_instance();
	 $data = array("secure"=> $word);
	 $c->session->set_userdata($data);
	 //$a = $c->session->userdata("secure");
	 // return $a;
 }
 
 
 // create password
 
 function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2) {
		$vowels .= "AEUY";
	}
	if ($strength & 4) {
		$consonants .= '23456789';
	}
	if ($strength & 8) {
		$consonants .= '@#$%';
	}
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}
 
 
 // send mail
 
   function send_email($email,$title, $body,$SiteName, $file_path='')

  {
		$SMTP_Host = "mail.nhunguyenco.com";
		$SMTP_Port = 25;
		$SMTP_UserName = "mail@nhunguyenco.com";
		$SMTP_Password = "123456";

  //  $email_list = $this->MHuman->get_email_list();


		
    //Initialize

		$mail = new PHPMailer();

		$mail->CharSet = 'utf-8';

		$mail->IsSMTP();
		
		//$mail->Host = $SMTP_Host;	
		
		$mail->Host     = $SMTP_Host;
		$mail->SMTPAuth = true;
		$mail->Username = $SMTP_UserName;
		$mail->Password = $SMTP_Password;
		
		
//		$mail->Username = "admin@queenlandmart.com.vn"; // your SMTP username or your gmail username

	//	$mail->Password = "admin"; //
			

//		$mail->Host = "mail.queenlandmart.com.vn";	
	
	//	$mail->Host = "mail.queenlandmart.com.vn"; // specify main and backup server

	//	$mail->Host = "localhost";

		$mail->From = $SMTP_UserName;//"admin@queenlandmart.com.vn";

		$mail->FromName = $SiteName;



		//send

 

      $mail->AddAddress($email);

 



//		$mail->AddReplyTo('qt_dat@yahoo.com');

		$mail->Subject  = $title;

		$mail->MsgHTML($body);

		$mail->IsHTML(true); // send as HTML



		//attach file

		if (!empty($file_path) && file_exists($file_path)) {

			$mail->AddAttachment($file_path);

		}



		if(!$mail->Send())

   		 {

			die($mail->ErrorInfo);

		}
		else
			return true;

  }
 
 
 
 
 
 

if ( ! function_exists('import_css')) {

	function import_css($src)

	{

    $result = '<link rel="stylesheet" type="text/css" ';

    $result .= 'href="'.base_url().'includes/css/'.$src.'"';

    $result .= '/>';



    echo $result;

	}

}
// CAPTCHA
function create_image(){
    //generate a random string
    $md5_hash = md5(rand(0,999));
	 
    //make it 5 characters long
    $security_code = substr($md5_hash, 15, 5); 

    //Storing the security code in the session
    $_SESSION["security_code"] = $security_code;

    //Create the image
    $image = @imagecreatefromjpeg("./images/home/static.jpg");  

    //Making the font color
    $black = ImageColorAllocate($image, 0, 0, 0);

    //Make the background black 
    //ImageFill($image, 0, 0, $bgImg); 

    //Set some variables for positioning and font-size, "5" is the largest I could get to work
	$vPos = 10;
	$hPos = 28;
	$fontSize = 5;
	
    ImageString($image, $fontSize, $hPos, $vPos, $security_code, $black); 
 
    //Tell the browser what kind of file this is 
    header("Content-Type: image/jpeg"); 

    //Output image as a jpeg 
    ImageJpeg($image);
   
    //Free up stuff
    ImageDestroy($image);
}
function catpcha()
{
	create_image();
	//exit();
}


// langauge
function set_lang($filename,$la="")
{
$l =  & get_instance();
if($la !="")
{
	$data["lang"] = $la;
}
else
{
	$data["lang"] = "vi";

}

//$l->session->set_userdata($data);
//$l->load->library('session');


$lang = $l->session->userdata("lang");
if($lang == "")
	$lang ="vi";

if($lang == "en")
	$language = "english";
else
	$language = "vietnamese";

$data["lang"] = $lang;
$l->session->set_userdata($data);
$l->lang->load($filename, $language);
return $lang;
}


// hit visitors



function hits_counter()
{
$CI = & get_instance();
$ip=$CI->input->ip_address();
// Check for previous visits
$query = $CI->db->get_where('hits', array('hit_ip' => $ip), 1, 0);
$query = $query->row_array();

if (count($query) < 1 )
{
    // Never visited - add
    $CI->db->insert('hits', array('hit_ip' => $ip) );
} 
return $CI->db->count_all('hits');
}

// count online
function cout_online()
{
	$CI = & get_instance();
	return $CI->db->count_all('ci_sessions');
}


// home link
function site_link($link)
{
	$dir = base_url()."index.php/".$link; 
	return $dir;
}
function site_link_img($link)
{
	$dir = base_url().$link; 
	return $dir;
}

if( !function_exists('html_decode')){
	function html_decode($data)
	{
		if($data != "" && !is_array($data)) return html_entity_decode($data,ENT_QUOTES,"UTF-8");
		return false;
	}
					 
					 
					 }

/**

 * Define javascript file

 */

if ( ! function_exists('import_js')) {

	function import_js($src)

	{

		$result = '<script type="text/javascript" ';

    $result .= 'src="'.base_url().'includes/js/'.$src.'"/>';

    $result .= '</script>';

    echo $result;

	}

}

/*** contact **/
function smcf_token($s) {
	return md5("smcf-" . $s . date("WY"));
}

// Validate and send email
function smcf_send($name, $email, $subject, $message, $cc) {
	global $to, $extra;

	// Filter and validate fields
	$name = smcf_filter($name);
	$subject = smcf_filter($subject);
	$email = smcf_filter($email);
	if (!smcf_validate_email($email)) {
		$subject .= " - invalid email";
		$message .= "\n\nBad email: $email";
		$email = $to;
		$cc = 0; // do not CC "sender"
	}

	// Add additional info to the message
	if ($extra["ip"]) {
		$message .= "\n\nIP: " . $_SERVER["REMOTE_ADDR"];
	}
	if ($extra["user_agent"]) {
		$message .= "\n\nUSER AGENT: " . $_SERVER["HTTP_USER_AGENT"];
	}

	// Set and wordwrap message body
	$body = "From: $name\n\n";
	$body .= "Message: $message";
	$body = wordwrap($body, 70);

	// Build header
	$headers = "From: $email\n";
	if ($cc == 1) {
		$headers .= "Cc: $email\n";
	}
	$headers .= "X-Mailer: PHP/SimpleModalContactForm";

	// UTF-8
	if (function_exists('mb_encode_mimeheader')) {
		$subject = mb_encode_mimeheader($subject, "UTF-8", "B", "\n");
	}
	else {
		// you need to enable mb_encode_mimeheader or risk 
		// getting emails that are not UTF-8 encoded
	}
	$headers .= "MIME-Version: 1.0\n";
	$headers .= "Content-type: text/plain; charset=utf-8\n";
	$headers .= "Content-Transfer-Encoding: quoted-printable\n";

	// Send email
	@sendmail() or 
		die("Unfortunately, a server issue prevented delivery of your message.");
}

// Remove any un-safe values to prevent email injection
function smcf_filter($value) {
	$pattern = array("/\n/","/\r/","/content-type:/i","/to:/i", "/from:/i", "/cc:/i");
	$value = preg_replace($pattern, "", $value);
	return $value;
}

// Validate email address format in case client-side validation "fails"
function smcf_validate_email($email) {
	$at = strrpos($email, "@");

	// Make sure the at (@) sybmol exists and  
	// it is not the first or last character
	if ($at && ($at < 1 || ($at + 1) == strlen($email)))
		return false;

	// Make sure there aren't multiple periods together
	if (preg_match("/(\.{2,})/", $email))
		return false;

	// Break up the local and domain portions
	$local = substr($email, 0, $at);
	$domain = substr($email, $at + 1);


	// Check lengths
	$locLen = strlen($local);
	$domLen = strlen($domain);
	if ($locLen < 1 || $locLen > 64 || $domLen < 4 || $domLen > 255)
		return false;

	// Make sure local and domain don't start with or end with a period
	if (preg_match("/(^\.|\.$)/", $local) || preg_match("/(^\.|\.$)/", $domain))
		return false;

	// Check for quoted-string addresses
	// Since almost anything is allowed in a quoted-string address,
	// we're just going to let them go through
	if (!preg_match('/^"(.+)"$/', $local)) {
		// It's a dot-string address...check for valid characters
		if (!preg_match('/^[-a-zA-Z0-9!#$%*\/?|^{}`~&\'+=_\.]*$/', $local))
			return false;
	}

	// Make sure domain contains only valid characters and at least one period
	if (!preg_match("/^[-a-zA-Z0-9\.]*$/", $domain) || !strpos($domain, "."))
		return false;	

	return true;
}
function sendmail()
{
	$title = "'Anh mười' - Thư Liên hệ ";
				$body = "Họ Tên: ".$this->input->post("name")."<br /> Từ Email:".$this->input->post("email")."<br />Tiêu Đề: ".$this->input->post("title")."<br />Nội dung: ".$this->input->post("detail");
			
				$email="tuong.dangman@gmail.com";
				$now = time();
				$data =array (
					'order_name' => $this->input->post("name"),
					'order_phone' => $this->input->post("phone"),
					'order_email' => $this->input->post("email"),
					'order_subject' => $this->input->post("title"),
					'order_detail' => $this->input->post("detail"),
						'order_modify' => $now,
					'order_status' => '0',
				);
				$c->load->model('Mproduct');
				 
				if(	$c->Mproduct->insert_order($data) &&send_email($email,$title, $body,'Anh mười') )
					return true;
				return false;
				
}



?>